package com.ibm.cps.servlet.starter;

import java.io.File;

import org.apache.log4j.Logger;

import com.ibm.util.ErrorCode;
import com.ibm.util.exception.CPSException;

public abstract class CommandlineStarter implements UserAppStarter{
	private final Logger logger = Logger.getLogger(this.getClass());
	protected final String shellPath;

	public CommandlineStarter(String path) {
		this.shellPath = path;
	}

	@Override
	public WorkerProcess start(String tenantId) throws CPSException {
		try {
			File f = new File(shellPath);
			if(!f.exists()){
				throw new CPSException(ErrorCode.INTERNAL_ERROR_CODE,
						"Cannot find starting shell script in " + shellPath);
			}
			String command = createShellCommand(tenantId);
			logger.info("start up command: " + command);
			Process process = Runtime.getRuntime().exec(command);
			CommandlineApp app = new CommandlineApp(process, tenantId);
			return app;
		} catch (CPSException e) {
			throw e;
		} catch (Exception e){
			throw new CPSException(ErrorCode.INTERNAL_ERROR_CODE,
					"Can't start or topology successfully.");
		}
	}
	
	public abstract String createShellCommand(String tenantId);

}
